import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:simple_app/common/api.dart';
import 'package:simple_app/common/global.dart';
import 'package:simple_app/common/model/accept.dart';

class AcceptListPage extends StatefulWidget {
  const AcceptListPage({Key? key}) : super(key: key);

  @override
  State<AcceptListPage> createState() => _AcceptListPageState();
}


//这里还需要增加寻找好友的功能icon，进入搜索页面

//申请列表
class _AcceptListPageState extends State<AcceptListPage> {
  var itemCount = 0;
  List<Accept> list = [];

  //列表数据
  Future<void> getList() async {
    var r = await Api().acceptList();
    if (r == null) {
      return;
    }
    if (r.statusCode != 200) {
      return;
    }
    if (r.statusCode == 200) {
      Map<String, dynamic> data = jsonDecode(r.body);
      if (data['status'] == 1) {
        List<dynamic> list2 = data['list'];
        setState(() {
          list.clear();
          for (var element in list2) {
            list.add(Accept.fromJson(element));
          }
          itemCount = list.length;
        });
      }
    }
    return;
  }

  var listenid = -1;

  @override
  void initState() {
    super.initState();
    getList();
    if (listenid == -1) {
      listenid = Global.listenMessage((jsonObj) {});
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (listenid != -1) {
      Global.removeListenMessage(listenid);
    }
  }

  Widget getState(int state, int index) {
    if (state == 1) {
      return const Text(
        '已接受',
        style: TextStyle(color: Color.fromARGB(255, 0, 200, 0)),
      );
    } else if (state == 2) {
      return const Text(
        '已拒绝',
        style: TextStyle(color: Color.fromARGB(255, 200, 0, 0)),
      );
    } else {
      return Row(
        children: [
          GestureDetector(
            onTap: () {
              print(index);
              print('accept!');
              Api().accept(list[index].id).then((response) {
                if (response == null) {
                  return;
                }
                if (response.statusCode != 200) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('服务器错误')),
                  );
                }
                var data = jsonDecode(response.body);
                if (data['status'] != 1) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text(data['info'])),
                  );
                } else {
                  //操作成功刷新列表
                  setState(() {
                    var last = list[index];
                    list.insert(
                        index,
                        Accept(
                            id: last.id,
                            friendId: last.friendId,
                            name: last.name,
                            state: 1,
                            denyReason: '',
                            addTime: last.addTime));
                  });
                  setState(() {
                    list.removeAt(index + 1);
                  });
                }
              });
            },
            child: const Text(
              '接受',
              style: TextStyle(color: Color.fromARGB(255, 0, 200, 0)),
            ),
          ),
          GestureDetector(
            onTap: () {
              print(index);
              print('deny!');
              Api().deny(list[index].id).then((response) {
                if (response == null) {
                  return;
                }
                if (response.statusCode != 200) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('服务器错误')),
                  );
                }
                var data = jsonDecode(response.body);
                if (data['status'] != 1) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text(data['info'])),
                  );
                } else {
                  //操作成功刷新列表
                  setState(() {
                    var last = list[index];
                    list.insert(
                        index,
                        Accept(
                            id: last.id,
                            friendId: last.friendId,
                            name: last.name,
                            state: 2,
                            denyReason: '',
                            addTime: last.addTime));
                  });
                  setState(() {
                    list.removeAt(index + 1);
                  });
                }
              });
            },
            child: Container(
              margin: const EdgeInsets.fromLTRB(8, 0, 0, 0),
              child: const Text(
                '拒绝',
                style: TextStyle(color: Color.fromARGB(255, 200, 0, 0)),
              ),
            ),
          )
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        onRefresh: onRefresh,
        child: ListView.builder(
            itemCount: itemCount,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(list[index].name),
                subtitle: getState(list[index].state, index),
              );
            }));
  }

  Future<void> onRefresh() {
    return getList();
  }
}
